<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-6xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">Screen Wake Lock API</h1>
        <p class="text-gray-300 text-lg">
          防止设备屏幕变暗或锁定，保持屏幕常亮
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300 mb-4">
          您的浏览器不支持 Screen Wake Lock API。此功能需要 Chrome 84+, Edge 84+ 或其他支持该 API 的浏览器。
        </p>
        <p class="text-gray-400 text-sm">
          注意：需要 HTTPS 环境或 localhost，且页面必须可见。
        </p>
      </div>

      <!-- 唤醒锁状态 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">唤醒锁状态</h2>
        
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
          <div class="bg-gray-800 rounded-lg p-6">
            <div class="text-gray-400 text-sm mb-2">锁定状态</div>
            <div class="flex items-center">
              <div
                class="w-4 h-4 rounded-full mr-3"
                :class="wakeLock ? 'bg-green-400 animate-pulse' : 'bg-gray-600'"
              ></div>
              <div class="text-white text-xl font-semibold">
                {{ wakeLock ? '已激活' : '未激活' }}
              </div>
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="text-gray-400 text-sm mb-2">激活次数</div>
            <div class="text-white text-2xl font-semibold">
              {{ activationCount }}
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="text-gray-400 text-sm mb-2">活动时长</div>
            <div class="text-white text-2xl font-semibold">
              {{ formatDuration(activeTime) }}
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="text-gray-400 text-sm mb-2">页面可见性</div>
            <div class="text-white text-2xl font-semibold">
              {{ isPageVisible ? '可见' : '隐藏' }}
            </div>
          </div>
        </div>

        <div class="flex gap-3">
          <button
            v-if="!wakeLock"
            @click="requestWakeLock"
            :disabled="!isSupported"
            class="tech-button disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-sun mr-2"></i>
            激活屏幕常亮
          </button>
          <button
            v-else
            @click="releaseWakeLock"
            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-moon mr-2"></i>
            释放唤醒锁
          </button>
        </div>
      </div>

      <!-- 使用场景演示 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">使用场景演示</h2>
        <p class="text-gray-300 mb-6">选择一个场景来体验屏幕常亮功能</p>
        
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
          <button
            @click="startScenario('reading')"
            :disabled="!isSupported"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-book text-3xl text-blue-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">阅读模式</div>
            <div class="text-gray-400 text-sm">长时间阅读，保持屏幕常亮</div>
          </button>

          <button
            @click="startScenario('cooking')"
            :disabled="!isSupported"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-restaurant text-3xl text-orange-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">烹饪助手</div>
            <div class="text-gray-400 text-sm">查看菜谱时保持屏幕亮起</div>
          </button>

          <button
            @click="startScenario('presentation')"
            :disabled="!isSupported"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-presentation-file text-3xl text-green-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">演示模式</div>
            <div class="text-gray-400 text-sm">展示内容时防止屏幕休眠</div>
          </button>

          <button
            @click="startScenario('navigation')"
            :disabled="!isSupported"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-location text-3xl text-purple-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">导航模式</div>
            <div class="text-gray-400 text-sm">使用地图导航时保持常亮</div>
          </button>

          <button
            @click="startScenario('video')"
            :disabled="!isSupported"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-video text-3xl text-red-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">视频播放</div>
            <div class="text-gray-400 text-sm">观看视频时防止息屏</div>
          </button>

          <button
            @click="startScenario('exercise')"
            :disabled="!isSupported"
            class="bg-gray-800 hover:bg-gray-700 text-white p-6 rounded-lg transition-colors text-left disabled:opacity-50 disabled:cursor-not-allowed"
          >
            <i class="i-carbon-activity text-3xl text-yellow-400 mb-3 block"></i>
            <div class="text-lg font-semibold mb-2">运动计时</div>
            <div class="text-gray-400 text-sm">健身计时时保持屏幕亮起</div>
          </button>
        </div>
      </div>

      <!-- 当前场景 -->
      <div v-if="currentScenario" class="tech-card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-semibold text-white">{{ scenarioInfo.title }}</h2>
          <button
            @click="stopScenario"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            <i class="i-carbon-stop-filled mr-1"></i>
            停止场景
          </button>
        </div>

        <div class="bg-gray-800 rounded-lg p-8 mb-6">
          <div class="flex items-center justify-center mb-6">
            <i :class="scenarioInfo.icon" class="text-6xl text-tech-accent"></i>
          </div>
          
          <div class="text-center">
            <div class="text-white text-xl font-semibold mb-2">
              {{ scenarioInfo.description }}
            </div>
            <div class="text-gray-400">
              已运行: {{ formatDuration(scenarioTime) }}
            </div>
          </div>
        </div>

        <div class="bg-gray-800 rounded-lg p-6">
          <h3 class="text-white font-semibold mb-3">场景说明</h3>
          <p class="text-gray-300 text-sm">
            {{ scenarioInfo.explanation }}
          </p>
        </div>
      </div>

      <!-- 页面可见性监控 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">页面可见性监控</h2>
        
        <div class="bg-gray-800 rounded-lg p-6">
          <div class="flex items-center justify-between mb-4">
            <div class="flex items-center">
              <div
                class="w-3 h-3 rounded-full mr-3"
                :class="isPageVisible ? 'bg-green-400' : 'bg-red-400'"
              ></div>
              <div class="text-white font-semibold">
                {{ isPageVisible ? '页面当前可见' : '页面已隐藏' }}
              </div>
            </div>
            <div class="text-gray-400 text-sm">
              可见次数: {{ visibilityChangeCount }}
            </div>
          </div>

          <div class="text-gray-300 text-sm space-y-2">
            <p>• 当页面切换到后台时，唤醒锁会自动释放</p>
            <p>• 当页面重新变为可见时，需要手动重新激活</p>
            <p>• 这是浏览器的安全机制，防止后台页面浪费电池</p>
          </div>
        </div>
      </div>

      <!-- 电池状态提示 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">电池影响提示</h2>
        
        <div class="bg-yellow-900/30 border border-yellow-600 rounded-lg p-6">
          <div class="flex items-start">
            <i class="i-carbon-warning text-yellow-400 text-2xl mr-4 mt-1"></i>
            <div>
              <h3 class="text-yellow-400 font-semibold mb-2">注意事项</h3>
              <ul class="text-gray-300 text-sm space-y-2">
                <li>• 保持屏幕常亮会增加电池消耗</li>
                <li>• 仅在必要时使用此功能</li>
                <li>• 在不需要时及时释放唤醒锁</li>
                <li>• 移动设备上电池消耗更明显</li>
                <li>• 建议配合降低屏幕亮度使用</li>
              </ul>
            </div>
          </div>
        </div>
      </div>

      <!-- 事件日志 -->
      <div v-if="logs.length > 0" class="tech-card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-semibold text-white">事件日志</h2>
          <button
            @click="clearLogs"
            class="text-red-400 hover:text-red-300 text-sm"
          >
            <i class="i-carbon-clean mr-1"></i>
            清空日志
          </button>
        </div>

        <div class="space-y-2 max-h-64 overflow-y-auto">
          <div
            v-for="(log, index) in logs.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-3 flex items-start text-sm"
          >
            <i
              :class="getLogIcon(log.type)"
              class="text-lg mr-3 mt-0.5"
            ></i>
            <div class="flex-1">
              <div class="text-white">{{ log.message }}</div>
              <div class="text-gray-400 text-xs mt-1">{{ log.timestamp }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>Chrome 84+, Edge 84+, Opera 70+</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要方法</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">navigator.wakeLock.request('screen')</code> - 请求唤醒锁</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">wakeLock.release()</code> - 释放唤醒锁</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">wakeLock.released</code> - 检查是否已释放</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">事件</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">release</code> - 唤醒锁被释放时触发</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>电子书阅读应用</li>
              <li>在线菜谱和烹饪应用</li>
              <li>演示和幻灯片应用</li>
              <li>导航和地图应用</li>
              <li>视频播放器</li>
              <li>健身和运动计时器</li>
              <li>扫码支付界面</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">工作原理</h4>
            <p class="text-sm leading-relaxed">
              Screen Wake Lock API 通过请求一个"唤醒锁"来防止设备屏幕变暗或关闭。
              这个锁只在页面可见时有效，当页面切换到后台或标签页被隐藏时，
              唤醒锁会自动释放。这是一个安全机制，防止后台页面持续消耗电池。
            </p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">自动释放条件</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>页面可见性变为隐藏（切换标签页、最小化窗口等）</li>
              <li>用户显式调用 <code class="bg-gray-800 px-1 rounded">release()</code></li>
              <li>页面被卸载或关闭</li>
              <li>设备电量过低（系统自动释放）</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">安全和隐私</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>需要 HTTPS 环境（localhost 除外）</li>
              <li>不需要用户授权（与通知等权限不同）</li>
              <li>页面必须可见才能激活</li>
              <li>浏览器可能在低电量时拒绝请求</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">最佳实践</h4>
            <ul class="list-disc list-inside space-y-1 text-sm">
              <li>只在真正需要时激活唤醒锁</li>
              <li>在用户完成操作后立即释放</li>
              <li>监听页面可见性变化，在页面重新可见时重新激活</li>
              <li>处理请求失败的情况（低电量、权限拒绝等）</li>
              <li>提供用户界面控制开关</li>
              <li>向用户说明为什么需要保持屏幕常亮</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">错误处理</h4>
            <div class="text-sm space-y-2">
              <p>请求唤醒锁可能失败的原因：</p>
              <ul class="list-disc list-inside space-y-1">
                <li><code class="bg-gray-800 px-1 rounded">NotAllowedError</code> - 页面不可见或权限被拒绝</li>
                <li><code class="bg-gray-800 px-1 rounded">NotSupportedError</code> - 浏览器不支持</li>
                <li>设备电量过低</li>
                <li>系统省电模式启用</li>
              </ul>
            </div>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">注意事项</h4>
            <ul class="list-disc list-inside space-y-1 text-sm text-yellow-400">
              <li>⚠️ 会显著增加电池消耗</li>
              <li>⚠️ 仅在页面可见时有效</li>
              <li>⚠️ 用户可能需要调整设备设置</li>
              <li>⚠️ 移动设备上的效果可能受系统限制</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'

// 类型定义
interface Log {
  type: 'info' | 'success' | 'warning' | 'error'
  message: string
  timestamp: string
}

interface ScenarioInfo {
  title: string
  description: string
  explanation: string
  icon: string
}

// 响应式状态
const isSupported = ref('wakeLock' in navigator)
const wakeLock = ref<any>(null)
const activationCount = ref(0)
const activeTime = ref(0)
const isPageVisible = ref(true)
const visibilityChangeCount = ref(0)

// 场景相关
const currentScenario = ref('')
const scenarioTime = ref(0)

// 日志
const logs = ref<Log[]>([])

// 定时器
let activeTimer: ReturnType<typeof setInterval> | null = null
let scenarioTimer: ReturnType<typeof setInterval> | null = null

// 场景信息
const scenarios: Record<string, ScenarioInfo> = {
  reading: {
    title: '阅读模式',
    description: '享受不间断的阅读体验',
    explanation: '在阅读电子书、文章或文档时，保持屏幕常亮可以避免频繁触碰屏幕来防止息屏，提供更好的阅读体验。',
    icon: 'i-carbon-book'
  },
  cooking: {
    title: '烹饪助手',
    description: '查看菜谱时保持屏幕亮起',
    explanation: '烹饪时双手可能忙碌或沾有食材，无法频繁触碰屏幕。保持屏幕常亮让您可以随时查看菜谱步骤。',
    icon: 'i-carbon-restaurant'
  },
  presentation: {
    title: '演示模式',
    description: '展示内容时防止屏幕休眠',
    explanation: '在演示幻灯片或展示内容时，保持屏幕常亮确保观众可以持续查看内容，避免尴尬的息屏情况。',
    icon: 'i-carbon-presentation-file'
  },
  navigation: {
    title: '导航模式',
    description: '使用地图导航时保持常亮',
    explanation: '在驾驶或步行导航时，保持屏幕常亮让您可以随时查看路线，无需频繁操作设备。',
    icon: 'i-carbon-location'
  },
  video: {
    title: '视频播放',
    description: '观看视频时防止息屏',
    explanation: '观看视频或直播时，保持屏幕常亮确保不会在精彩时刻突然息屏，提供连续的观看体验。',
    icon: 'i-carbon-video'
  },
  exercise: {
    title: '运动计时',
    description: '健身计时时保持屏幕亮起',
    explanation: '在进行健身训练或瑜伽时，保持屏幕常亮让您可以随时查看计时器和动作指导，无需中断训练。',
    icon: 'i-carbon-activity'
  }
}

const scenarioInfo = computed(() => {
  return currentScenario.value ? scenarios[currentScenario.value] : null
})

// 初始化
onMounted(() => {
  // 监听页面可见性变化
  document.addEventListener('visibilitychange', handleVisibilityChange)
  isPageVisible.value = !document.hidden
})

// 清理
onUnmounted(() => {
  document.removeEventListener('visibilitychange', handleVisibilityChange)
  releaseWakeLock()
  stopTimers()
})

// 请求唤醒锁
const requestWakeLock = async () => {
  if (!isSupported.value) {
    addLog('error', '浏览器不支持 Wake Lock API')
    return
  }

  try {
    addLog('info', '正在请求屏幕唤醒锁...')
    
    wakeLock.value = await (navigator as any).wakeLock.request('screen')
    activationCount.value++
    
    // 监听释放事件
    wakeLock.value.addEventListener('release', () => {
      addLog('info', '唤醒锁已被释放')
      wakeLock.value = null
      stopTimers()
    })
    
    addLog('success', '屏幕唤醒锁已激活')
    startTimer()
    
  } catch (err) {
    console.error('请求唤醒锁失败:', err)
    
    if (err instanceof Error) {
      if (err.name === 'NotAllowedError') {
        addLog('error', '无法激活：页面不可见或权限被拒绝')
      } else if (err.name === 'NotSupportedError') {
        addLog('error', '浏览器不支持此功能')
      } else {
        addLog('error', `激活失败: ${err.message}`)
      }
    } else {
      addLog('error', '激活唤醒锁失败')
    }
  }
}

// 释放唤醒锁
const releaseWakeLock = async () => {
  if (!wakeLock.value) return

  try {
    await wakeLock.value.release()
    wakeLock.value = null
    addLog('success', '唤醒锁已手动释放')
    stopTimers()
  } catch (err) {
    console.error('释放唤醒锁失败:', err)
    addLog('error', '释放失败')
  }
}

// 开始场景
const startScenario = async (scenario: string) => {
  currentScenario.value = scenario
  scenarioTime.value = 0
  
  // 激活唤醒锁
  await requestWakeLock()
  
  // 开始场景计时
  scenarioTimer = setInterval(() => {
    scenarioTime.value++
  }, 1000)
  
  addLog('info', `开始场景: ${scenarios[scenario].title}`)
}

// 停止场景
const stopScenario = () => {
  if (currentScenario.value) {
    addLog('info', `停止场景: ${scenarios[currentScenario.value].title}`)
  }
  
  currentScenario.value = ''
  scenarioTime.value = 0
  
  if (scenarioTimer) {
    clearInterval(scenarioTimer)
    scenarioTimer = null
  }
  
  releaseWakeLock()
}

// 处理页面可见性变化
const handleVisibilityChange = () => {
  isPageVisible.value = !document.hidden
  visibilityChangeCount.value++
  
  if (document.hidden) {
    addLog('warning', '页面已隐藏，唤醒锁将自动释放')
  } else {
    addLog('info', '页面重新可见')
    
    // 如果有活动的场景，重新激活唤醒锁
    if (currentScenario.value && !wakeLock.value) {
      addLog('info', '场景仍在运行，重新激活唤醒锁')
      requestWakeLock()
    }
  }
}

// 开始计时
const startTimer = () => {
  activeTime.value = 0
  activeTimer = setInterval(() => {
    activeTime.value++
  }, 1000)
}

// 停止计时器
const stopTimers = () => {
  if (activeTimer) {
    clearInterval(activeTimer)
    activeTimer = null
  }
  activeTime.value = 0
}

// 格式化时长
const formatDuration = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60

  if (hours > 0) {
    return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
  }
  return `${minutes}:${secs.toString().padStart(2, '0')}`
}

// 添加日志
const addLog = (type: 'info' | 'success' | 'warning' | 'error', message: string) => {
  logs.value.push({
    type,
    message,
    timestamp: new Date().toLocaleTimeString('zh-CN')
  })

  // 只保留最近 50 条
  if (logs.value.length > 50) {
    logs.value.shift()
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 获取日志图标
const getLogIcon = (type: string) => {
  const icons = {
    info: 'i-carbon-information-filled text-blue-400',
    success: 'i-carbon-checkmark-filled text-green-400',
    warning: 'i-carbon-warning-filled text-yellow-400',
    error: 'i-carbon-error-filled text-red-400'
  }
  return icons[type as keyof typeof icons]
}
</script>

